//
// Created by denglibin on 2021/4/10 0010.
//
#include "game.h"
#include "stdlib.h"
#include "load.h"
#include "draw.h"
#include "time.h"
#define WIN_WIDTH 800
#define WIN_HEIGHT 360
#define FRAME_RATE 60 //帧率

/**
 * 初始化
 */
static void init();
/**
 * 创建游戏对象
 * @return
 */
Game * GM_createGame(const char* gameName){
    Game* game =  (Game*)calloc(1, sizeof(Game));
    GameWindow * window = GW_createGameWindow(WIN_WIDTH, WIN_HEIGHT, gameName);
    game->gameWindow = window;
    gameLoad(game);//加载资源

    //游戏事件循环
    GM_eventLoop(game);
    return game;
}

void GM_paint(Game* game){
    //绘制背景
    drawBg(game->bg, game->gameWindow, game->spirit->x);
    //绘制精灵
    drawSpirit(game);
}


void GM_eventLoop(Game* game){
   GameWindow * gameWindow = game->gameWindow;
    SDL_Event  event;
    while (1)
    {//主消息循环
        while (SDL_PollEvent(&event)){
            switch (event.type) {
                case SDL_QUIT:
                    return;
                case SDL_KEYDOWN:
                {
                    switch (event.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            return;
                        case SDLK_d:
                        {
                            if(game->spirit->x < game->bg->width - game->spirit->w){
                                game->spirit->x+=game->spirit->speed;
                            }
                            break;
                        }
                        case SDLK_a:
                        {
                            if(game->spirit->x > 0){
                                game->spirit->x-=game->spirit->speed;
                            }
                            break;
                        }
                    }
                }
                    break;
            }
        }
        //设置渲染器颜色
        SDL_SetRenderDrawColor(gameWindow->sdl_win_renderer, 0, 0, 0, 255);
        SDL_RenderClear(gameWindow->sdl_win_renderer); //用设置的颜色清除
        GM_paint(game); //调用绘制函数
        //生效
        SDL_RenderPresent(gameWindow->sdl_win_renderer);

        uint32_t  begin = SDL_GetTicks();
        uint32_t  end = SDL_GetTicks();
        uint32_t  cost = end - begin;
        uint32_t per_frame_time = 1000 / FRAME_RATE;//每一帧耗时ms
        if (per_frame_time > cost){
            //减去循环体耗时，得到还应休眠的时间
            SDL_Delay(per_frame_time - cost);
        }
    }

}

/**
 * 开始游戏
 * @param game
 */
void GM_startGame(Game* game){

}

/**
 * 释放游戏资源
 */
void GM_freeGame(Game * game){
    if(game == NULL){
        return;
    }
    BG_freeBg(game->bg);
    SP_freeSpirit(game->spirit);
    GW_freeGameWindow(game->gameWindow);
    free(game);
}


static void init(){
    //随机数种子
    srand((unsigned)time(NULL));
}



